<template>
  <div class="app-container">
    <el-container class="main-container">
      <!-- 侧边栏导航 -->
      <el-aside
        :width="isSidebarCollapse ? '64px' : '240px'"
        class="sidebar"
        :class="{ 'collapse': isSidebarCollapse }"
      >
        <div class="logo-container">
          <img src="/logo.svg" alt="Logo" class="logo-image" v-if="!isSidebarCollapse">
          <h1 class="logo-text" v-if="!isSidebarCollapse">智能交通监控系统</h1>
          <img src="/logo-small.svg" alt="Logo" class="logo-image-small" v-else>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          background-color="#001529"
          text-color="#fff"
          active-text-color="#1890ff"
          router
          :collapse="isSidebarCollapse"
          :collapse-transition="false"
        >
          <el-menu-item index="/dashboard">
            <el-icon><PieChart /></el-icon>
            <template #title>数据看板</template>
          </el-menu-item>
          <el-menu-item index="/cameras">
            <el-icon><VideoCamera /></el-icon>
            <template #title>摄像头监控</template>
          </el-menu-item>
          <el-menu-item index="/scene-management">
            <el-icon><Layout /></el-icon>
            <template #title>场景管理</template>
          </el-menu-item>
          <el-menu-item index="/file-detection">
            <el-icon><Upload /></el-icon>
            <template #title>文件检测</template>
          </el-menu-item>
          <el-menu-item index="/alerts">
            <el-icon><Warning /></el-icon>
            <template #title>
              告警管理
              <el-badge :value="unprocessedAlerts" class="alert-badge" v-if="unprocessedAlerts > 0" />
            </template>
          </el-menu-item>
          <el-menu-item index="/statistics">
            <el-icon><TrendCharts /></el-icon>
            <template #title>统计分析</template>
          </el-menu-item>
          <el-menu-item index="/system">
            <el-icon><Setting /></el-icon>
            <template #title>系统设置</template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <!-- 主内容区域 -->
      <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="top-header">
          <div class="header-left">
            <el-icon class="menu-toggle" @click="toggleSidebar"><Menu /></el-icon>
            <breadcrumb :routes="route.matched" />
          </div>
          <div class="header-right">
            <!-- 通知下拉菜单 -->
            <el-dropdown trigger="click" @command="handleNotificationCommand" class="notification-dropdown">
              <span class="notification-icon">
                <el-icon><Bell /></el-icon>
                <el-badge :value="notificationCount" class="notification-badge" v-if="notificationCount > 0" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item disabled class="notification-header">
                    <div class="notification-title">通知消息</div>
                    <div class="notification-clear" @click.stop="clearNotifications">全部清空</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="notifications.length === 0" disabled>
                    暂无通知
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-for="notification in notifications.slice(0, 5)"
                    :key="notification.id"
                    :command="notification"
                    class="notification-item"
                    :class="`notification-${notification.type || 'info'}`"
                  >
                    <div class="notification-content">
                      <div class="notification-message">{{ notification.message }}</div>
                      <div class="notification-time">{{ formatNotificationTime(notification.timestamp) }}</div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="notifications.length > 5" 
                    divided 
                    class="notification-more"
                  >
                    查看更多
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <!-- 用户信息 -->
            <el-dropdown trigger="click" @command="handleUserCommand">
              <span class="user-avatar">
                <el-avatar :size="36" :src="userAvatar || '/avatar.svg'">管</el-avatar>
                <span class="username">{{ userName || '管理员' }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    <span>个人设置</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 页面内容 -->
        <el-main class="page-content">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
    
    <!-- 全局通知组件 -->
    <Notification />
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  PieChart, 
  VideoCamera, 
  Upload, 
  Warning, 
  TrendCharts, 
  Setting, 
  Menu, 
  Bell, 
  User, 
  SwitchButton,
  Layout 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Notification from './components/Notification.vue'
import store from './store'
import api from './api/apiService'

// 动态导入面包屑组件
const Breadcrumb = () => import('./components/Breadcrumb.vue')

export default {
  name: 'App',
  components: {
    PieChart,
    VideoCamera,
    Upload,
    Warning,
    TrendCharts,
    Setting,
    Menu,
    Bell,
    User,
    SwitchButton,
    Layout,
    Notification,
    Breadcrumb
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const isSidebarCollapse = ref(false)
    const userName = ref('')
    const userAvatar = ref('')
    
    // 计算属性
    const activeMenu = computed(() => {
      return route.path || '/dashboard'
    })
    
    // 从store获取通知和统计数据
    const notifications = computed(() => store.state.notifications)
    const notificationCount = computed(() => notifications.value.length)
    const unprocessedAlerts = computed(() => store.state.statistics.unprocessedAlerts || 0)
    
    // 切换侧边栏
    const toggleSidebar = () => {
      isSidebarCollapse.value = !isSidebarCollapse.value
      store.actions.toggleSidebar()
    }
    
    // 处理通知命令
    const handleNotificationCommand = (notification) => {
      console.log('处理通知:', notification)
      // 标记通知为已读
      store.actions.removeNotification(notification.id)
      
      // 如果是告警通知，跳转到告警详情
      if (notification.type === 'warning' && notification.alertId) {
        router.push(`/alerts/detail/${notification.alertId}`)
      }
    }
    
    // 处理用户命令
    const handleUserCommand = (command) => {
      switch (command) {
        case 'profile':
          ElMessage.info('个人设置功能待开发')
          break
        case 'logout':
          confirmLogout()
          break
      }
    }
    
    // 确认退出登录
    const confirmLogout = () => {
      ElMessageBox.confirm('确定要退出登录吗？', '退出登录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除登录状态
        localStorage.removeItem('token')
        ElMessage.success('已退出登录')
        // 可以根据需要跳转到登录页
      }).catch(() => {
        // 用户取消退出
      })
    }
    
    // 清空通知
    const clearNotifications = () => {
      store.actions.clearNotifications()
    }
    
    // 格式化通知时间
    const formatNotificationTime = (timestamp) => {
      if (!timestamp) return ''
      
      const now = new Date()
      const notificationTime = new Date(timestamp)
      const diffMs = now - notificationTime
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMs / 3600000)
      
      if (diffMins < 1) return '刚刚'
      if (diffMins < 60) return `${diffMins}分钟前`
      if (diffHours < 24) return `${diffHours}小时前`
      
      return notificationTime.toLocaleDateString('zh-CN')
    }
    
    // 监听路由变化，更新页面标题
    watch(() => route.path, (newPath) => {
      const titleMap = {
        '/dashboard': '数据看板 - 智能交通监控系统',
        '/cameras': '摄像头监控 - 智能交通监控系统',
        '/file-detection': '文件检测 - 智能交通监控系统',
        '/alerts': '告警管理 - 智能交通监控系统',
        '/statistics': '统计分析 - 智能交通监控系统',
        '/system': '系统设置 - 智能交通监控系统'
      }
      
      document.title = titleMap[newPath] || '智能交通监控系统'
    }, { immediate: true })
    
    // 页面加载时初始化数据
    onMounted(async () => {
      console.log('智能交通监控系统已启动')
      
      try {
        // 设置用户信息
        userName.value = '管理员'
        
        // 暂时不获取统计数据，避免API错误
        console.log('应用已启动，跳过统计数据获取')
        
        // 添加欢迎通知
        store.actions.addNotification({
          type: 'success',
          title: '欢迎回来',
          message: '您已成功登录智能交通监控系统',
          autoDismiss: true
        })
        
      } catch (error) {
        console.error('初始化错误:', error)
        // 添加错误通知
        store.actions.addNotification({
          type: 'error',
          title: '初始化失败',
          message: '无法连接到后端服务，请检查网络连接',
          autoDismiss: true
        })
      }
    })
    
    return {
      route,
      activeMenu,
      isSidebarCollapse,
      userName,
      userAvatar,
      notifications,
      notificationCount,
      unprocessedAlerts,
      toggleSidebar,
      handleNotificationCommand,
      handleUserCommand,
      clearNotifications,
      formatNotificationTime
    }
  }
}
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  background-color: #f0f2f5;
  color: #303133;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.app-container {
  height: 100vh;
  overflow: hidden;
}

.main-container {
  height: 100%;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #001529;
  overflow: hidden;
  transition: width 0.3s, background-color 0.3s;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #002140;
  padding: 0 20px;
  transition: all 0.3s;
}

.logo-image {
  height: 32px;
  margin-right: 10px;
}

.logo-image-small {
  height: 24px;
}

.logo-text {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sidebar-menu {
  border-right: none;
  height: calc(100vh - 60px);
}

.sidebar-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
  margin: 0;
  transition: all 0.3s;
}

.sidebar-menu .el-menu-item:hover {
  background-color: #1f2937;
}

.alert-badge {
  margin-left: 5px;
}

/* 顶部导航栏样式 */
.top-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  padding: 0 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
  flex: 1;
}

.menu-toggle {
  cursor: pointer;
  font-size: 20px;
  color: #606266;
  transition: color 0.3s;
  padding: 8px;
  border-radius: 4px;
}

.menu-toggle:hover {
  color: #1890ff;
  background-color: #f5f7fa;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

/* 通知样式 */
.notification-dropdown {
  position: relative;
}

.notification-icon {
  position: relative;
  font-size: 20px;
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;
  padding: 8px;
  border-radius: 4px;
}

.notification-icon:hover {
  color: #1890ff;
  background-color: #f5f7fa;
}

.notification-badge {
  position: absolute;
  top: -4px;
  right: -4px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px !important;
  height: 40px;
}

.notification-title {
  font-weight: 600;
  color: #303133;
}

.notification-clear {
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
}

.notification-clear:hover {
  text-decoration: underline;
}

.notification-item {
  padding: 12px 20px !important;
  cursor: pointer;
}

.notification-item .notification-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notification-item .notification-message {
  color: #303133;
  line-height: 1.4;
}

.notification-item .notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-success {
  background-color: #f0f9eb;
}

.notification-warning {
  background-color: #fdf6ec;
}

.notification-error {
  background-color: #fef0f0;
}

.notification-info {
  background-color: #edf2fc;
}

.notification-more {
  text-align: center;
  cursor: pointer;
}

/* 用户信息样式 */
.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: #f5f7fa;
}

.username {
  margin-left: 10px;
  font-size: 14px;
  white-space: nowrap;
}

/* 页面内容区域样式 */
.page-content {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  overflow-y: auto;
  transition: padding 0.3s;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .sidebar {
    width: 200px;
  }
  
  .sidebar.collapse {
    width: 64px;
  }
  
  .logo-text {
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    height: 100vh;
    transform: translateX(0);
    transition: transform 0.3s;
  }
  
  .sidebar.collapse {
    transform: translateX(-100%);
    width: 240px;
  }
  
  .page-content {
    padding: 16px;
  }
  
  .top-header {
    padding: 0 16px;
  }
  
  .header-left {
    gap: 16px;
  }
  
  .header-right {
    gap: 16px;
  }
  
  .username {
    display: none;
  }
}

@media (max-width: 480px) {
  .page-content {
    padding: 12px;
  }
}
</style>